/**
 * Task 中间件
 * 帮助完成方法传递。
 * 运行函数内部，this 指针会出现丢失，如果需要使用this，推荐箭头函数: () => {}
 * @author aker
 * @date 2019-7-10
 */

interface IMiddleware {
  [key:string]: Function[]
}

export default class MiddlewareClass {
  public static middlewares:IMiddleware = {}
  static regist(key:string, middlewares:Function[], ...params:any[]) {
    if (!this.middlewares[key]) {
      this.middlewares[key] = middlewares
    }
    const currentMiddleware = new MiddlewareClass(middlewares, params)
    currentMiddleware.route = key
    currentMiddleware.startGenerateMiddles(this.middlewares[key], params)
  }

  index:number //简单用计数实现
  middlewares:Function[]
  params:any[]
  route:string
  constructor (middlewares:Function[], params:any[]) {
    this.index = -1
    this.middlewares = middlewares
    this.params = params
  }
  startGenerateMiddles(middlewares:Function[], params:any[]) {
    if (this.index >= middlewares.length) return
    this.index ++
    // 下面这句解释出来是apply(middlewares[0], ...), this 变成了request 方法
    const func = middlewares[this.index]
    // printlog(`[SimpleMiddleware.startGenerateMiddles] route:${this.route} index:${this.index}`, func)
    func(...params, this.next)
  }
  next = () => {
    this.startGenerateMiddles(this.middlewares, this.params)
  }
}